var SHAKE_THRESHOLD = 450;    
var last_update = 0;    
var x, y, z, last_x, last_y, last_z;  

function deviceMotionHandler(eventData) {  
    var acceleration = eventData.accelerationIncludingGravity;  
    var html = '<p>' + acceleration.x.toFixed(1) + '</p>';
    html += '<p>' + acceleration.y.toFixed(1) + '</p>';
    html += '<p>' + acceleration.z.toFixed(1) + '</p>';
    $('.test').html(html);

    var curTime = new Date().getTime();//获取当前时间戳
    var diffTime = curTime - last_update;
    if (diffTime > SHAKE_THRESHOLD) {
        last_update = curTime;//记录上一次摇动的时间
        x = acceleration.x;//获取加速度X方向
        y = acceleration.y;//获取加速度Y方向
        z = acceleration.z;//获取加速度垂直方向
        var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;//计算阈值
        if (speed > SHAKE_THRESHOLD) {
            shakeAction();
        }
        //记录上一次加速度
        last_x = x;
        last_y = y;
        last_z = z;
    }
}  

function bindShake() {
    if (window.DeviceMotionEvent) {  
        window.addEventListener('devicemotion',deviceMotionHandler, false);  
    }
}
function unBindShake() {
    if (window.DeviceMotionEvent) {  
        window.removeEventListener('devicemotion',deviceMotionHandler, false);  
    }
}